package com.readfeed.app.data;

import java.util.ArrayList;

import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class CategoriesTable {
	public static final String TABLE_CATEGORIES_NAME = "categories";
	public static final String COLUMN_ID = "_id";
	public static final String COLUMN_TITLE = "title";
	
	public static final String CATEGORY_SPORT = "Sport";
	public static final String CATEGORY_ENTERTAINMENT = "Entertainment";
	public static final String CATEGORY_NEWS = "News";
	public static final String CATEGORY_OTHERS = "Others";
	
	private static final String DATABASE_CREATE = "create table " 
		      + TABLE_CATEGORIES_NAME
		      + "(" 
		      + COLUMN_ID + " integer primary key autoincrement, " 
		      + COLUMN_TITLE + " text not null);"; 
			
	public static void onCreate(SQLiteDatabase database){
		database.execSQL(DATABASE_CREATE);
		populateTable(database);
	}
	
	private static void populateTable(SQLiteDatabase database){
		database.beginTransaction();
		try{
			ArrayList<ContentValues> contentValuesList = new ArrayList<ContentValues>();
			ContentValues newsCat = new ContentValues();
			newsCat.put(COLUMN_TITLE, CATEGORY_NEWS);
			
			ContentValues sportCat = new ContentValues();
			sportCat.put(COLUMN_TITLE, CATEGORY_SPORT);
			
			ContentValues entertainmentCat = new ContentValues();			
			entertainmentCat.put(COLUMN_TITLE, CATEGORY_ENTERTAINMENT);
			
			ContentValues othersCat = new ContentValues();
			othersCat.put(COLUMN_TITLE, CATEGORY_OTHERS);
			
			contentValuesList.add(newsCat);
			contentValuesList.add(sportCat);
			contentValuesList.add(entertainmentCat);
			contentValuesList.add(othersCat);
			
			for (int i = 0; i < contentValuesList.size(); i++) {
				ContentValues value = contentValuesList.get(i);
				database.insert(TABLE_CATEGORIES_NAME, null, value);
			}
			
			database.setTransactionSuccessful();
		} finally {
			database.endTransaction();
		}
	}
	
	public static void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion){
		Log.w(CategoriesTable.class.getName(), "Upgrading database from version "
		        + oldVersion + " to " + newVersion);
		    database.execSQL("DROP TABLE IF EXISTS " + TABLE_CATEGORIES_NAME);
		    onCreate(database);
	}
}
